
const { docSchedulingModel, OrderModel, userModel } = require("../model");

//将小时和分钟转成数字类型
function timeStringToNumber(timeString) {
  // 验证时间字符串格式
  const timeRegex = /^([01]\d|2[0-3]):([0-5]\d)$/;
  if (!timeRegex.test(timeString)) {
    throw new Error("Invalid time format. Expected format is HH:MM.");
  }

  // 分割小时和分钟
  const [hours, minutes] = timeString.split(":").map(Number);

  // 拼接小时和分钟为一个数字
  const timeNumber = hours * 100 + minutes;

  return timeNumber;
}
function getCurrentTimeAsNumber() {
  // 获取当前日期和时间
  const now = new Date();

  // 获取当前小时（0-23）
  const hours = now.getHours();

  // 获取当前分钟（0-59）
  const minutes = now.getMinutes();

  // 如果小时或分钟是个位数，前面补零
  const formattedHours = hours < 10 ? "0" + hours : hours;
  const formattedMinutes = minutes < 10 ? "0" + minutes : minutes;

  // 拼接小时和分钟为一个字符串
  const timeString = formattedHours + formattedMinutes;

  // 将字符串转换为数字
  const timeNumber = parseInt(timeString, 10);

  return timeNumber;
}
//添加订单
exports.addOrder = async (req, res) => {
  const { patientId, doctorId, scheduleId } = req.body;
  if (!patientId || !doctorId || !scheduleId) {
    return res.status(400).json({
      code: 400,
      message: "缺少必要参数",
      data: null,
    });
  }
  //同一个就诊人不能在一个排班里重复预约挂号
  let order = await OrderModel.findOne({ patientId, scheduleId });
  if (order&&order.registerStatus!==2) {
    return res.status(400).json({
      code: 400,
      message: "同一个就诊人不能在一个排班里重复预约挂号",
      data: null,
    });
  }
  let sch = await docSchedulingModel.findOne({ _id: scheduleId });
  if (sch.status == 1) {
    return res.status(400).json({
      code: 400,
      message: "当前排班已关闭",
      data: null,
    });
  }
  if (sch.currentNumber <= 0 || sch.status == 2 ) {
    return res.status(400).json({
      code: 400,
      message: "当前排班已约满",
      data: null,
    });
  }
  //排班表对应排班人数-1
  sch.currentNumber--;
  await sch.save();
  //像订单表中添加一条数据
  let dbBack = new OrderModel({
    userId: req.user._id,
    patientId,
    scheduleId,
    doctorId,
  });
  try {
    let result = await dbBack.save();
    res.status(200).json({
      code: 200,
      message: "添加订单成功",
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "添加订单失败",
      data: error,
    });
  }
};
//获取订单列表
exports.getOrderList = async (req, res) => {
  const { pageNo = 1, pageSize = 10 } = req.query;
  const { patientId } = req.body;
  let userId = req.user._id;
  try {
    if (!patientId) {
      //如果没有对应的就诊人id就查询对应用户id的所有订单
      let result = await OrderModel.find({ userId })
        .skip((pageNo - 1) * pageSize)
        .limit(pageSize)
        .populate("userId")
        .populate("patientId")
        .populate("scheduleId")
        .populate({
          path:'doctorId',
          model:'Hospital',
          populate:{
            path:'job',
            model:'Job'
          }
        });
      let total = (await OrderModel.find({ userId })).length;
      return res.status(200).json({
        code: 200,
        message: "获取订单列表成功",
        data: result,
        total,
      });
    } else {
      let result = await OrderModel.find({ patientId })
        .skip((pageNo - 1) * pageSize)
        .limit(pageSize)
        .populate("userId")
        .populate("patientId")
        .populate("scheduleId")
        .populate("doctorId");
      let total = (await OrderModel.find({ patientId })).length;
      return res.status(200).json({
        code: 200,
        message: "获取订单列表成功",
        data: result,
        total,
      });
    }
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单列表失败",
      data: error,
    });
  }
};
//取消订单
exports.cancelOrder = async (req, res) => {
  const { orderId } = req.query;
  if (!orderId) {
    return res.status(400).json({
      code: 400,
      message: "缺少必要参数",
      data: null,
    });
  }
  try {
    //查询订单的状态，如果订单状态为待支付 0 则可以取消订单,同时将订单剩余挂号人数+1
    let result = await OrderModel.findById(orderId);
    if (result.registerStatus == 0) {
      //将订单状态改为已取消
      result.registerStatus = 2;
      //将订单剩余挂号人数+1
      let sch = await docSchedulingModel.findById(result.scheduleId);
      sch.currentNumber++;
      await sch.save();
      await result.save();
      return res.status(200).json({
        code: 200,
        message: "取消订单成功",
        data: null,
      });
    }
    //如果订单状态为已支付 1 ,就先判断是否在有效期内，如果在有效期内则可以取消订单，同时将订单剩余挂号人数+1,否则就不允许取消挂号
    else if (result.registerStatus == 1) {
      let sch = await docSchedulingModel.findById(result.scheduleId);
      if (sch.status == 1) {
        return res.status(400).json({
          code: 400,
          message: "当前排班已关闭,无法取消",
          data: null,
        });
      }
      if (getCurrentTimeAsNumber() >= timeStringToNumber(sch.endTime)) {
        return res.status(400).json({
          code: 400,
          message: "订单已过期，无法取消",
          data: null,
        });
      } else if (
        timeStringToNumber(sch.endTime) - getCurrentTimeAsNumber() <=
        30
      ) {
        return res.status(400).json({
          code: 400,
          message: "订单在30分钟内无法取消",
          data: null,
        });
      } else {
        //将订单状态改为已取消
        result.registerStatus = 2;
        //将订单剩余挂号人数+1
        sch.currentNumber++;
        //查询用户
        let user = await userModel.findById(req.user._id);
        //将用户账户余额加上订单金额
        user.money += sch.price;
        await sch.save();
        await result.save();
        await user.save();
        return res.status(200).json({
          code: 200,
          message: "取消订单成功",
          data: null,
        });
      }
    }
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "取消订单失败",
      data: error,
    });
  }
};
//支付订单
exports.payOrder = async (req, res) => {
  const { orderId } = req.query;
  if (!orderId) {
    return res.status(400).json({
      code: 400,
      message: "缺少必要参数",
      data: null,
    });
  }
  try {
    //查到对应的订单号,并且将订单状态改为已支付,而且将订单剩余挂号人数-1,
    //同时将用户账户余额减去订单金额(判断金额是否足够)
    let order = await OrderModel.findById(orderId).populate("scheduleId");
    let user = await userModel.findById(req.user._id);
    let sch = await docSchedulingModel.findById(order.scheduleId);
    if (user.money < sch.price) {
      return res.status(400).json({
        code: 400,
        message: "账户余额不足",
        data: null,
      });
    }
    if (order.registerStatus == 1) {
      return res.status(400).json({
        code: 400,
        message: "订单已支付",
        data: null,
      });
    }
    if (order.registerStatus == 2) {
      return res.status(400).json({
        code: 400,
        message: "订单已取消,请重新预约",
        data: null,
      });
    }
    if (sch.currentNumber <= 0) {
      return res.status(400).json({
        code: 400,
        message: "当前排班已约满",
        data: null,
      });
    }
    if (sch.status == 1) {
      order.registerStatus = 2;
      await order.save();
      return res.status(400).json({
        code: 400,
        message: "当前排班已关闭,以自动取消该预约",
        data: null,
      })
    }
    //将订单状态改为已支付
    order.registerStatus = 1;
    //将订单剩余挂号人数-1
    sch.currentNumber--;
    //将用户账户余额减去订单金额
    user.money -= sch.price;
    await order.save();
    await sch.save();
    await user.save();
    return res.status(200).json({
      code: 200,
      message: "支付订单成功",
      data: null,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "支付订单失败",
      data: error,
    });
  }
};
//获取订单详情
exports.getOrderDetail = async (req, res) => {
  const { orderId } = req.query;
  if (!orderId) {
    return res.status(400).json({
      code: 400,
      message: "缺少必要参数",
      data: null,
    });
  }
  try {
    let result = await OrderModel.findById(orderId)
      .populate("userId")
      .populate("patientId")
      .populate("scheduleId")
      .populate({
        path:'doctorId',
        model:'Hospital',
        populate:{
          path:'job',
          model:'Job'
        }
      });
    res.status(200).json({
      code: 200,
      message: "获取订单详情成功",
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单详情失败",
      data: error,
    });
  }
};
//获取所有订单列表
exports.getAdminOrderList = async (req, res) => {
  const { pageNo = 1, pageSize = 10 } = req.query;
  try {
    let result = await OrderModel.find()
      .skip((pageNo - 1) * pageSize)
      .limit(pageSize)
      .populate("userId")
      .populate("patientId")
      .populate("scheduleId")
      .populate({
        path: "doctorId",
        model: "Hospital",
        populate: {
          path: "job",
          model: "Job",
        }
      });
    let total = (await OrderModel.find()).length;
    res.status(200).json({
      code: 200,
      message: "获取订单列表成功",
      data: result,
      total
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单列表失败",
      data: error
    });
  }
};
